package wnhz.com.business.groupshop.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseFragment;
import wnhz.com.business.base.BaseRecyclerAdapter;
import wnhz.com.business.groupshop.adapter.FragmentFifthAdapter;
import wnhz.com.business.groupshop.bean.OrderBean;
import wnhz.com.business.groupshop.ui.EvaluateActivity;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.uitls.decoration.HorizDecoration;
import wnhz.com.business.uitls.dialog.SimpleDialog;

import static android.app.Activity.RESULT_OK;

public class OrderFivthFragment extends BaseFragment implements BaseRecyclerAdapter.OnDataLoadFinish{

    @BindView(R.id.recycler_View)
    RecyclerView recyclerView;
    @BindView(R.id.empty_layout)
    LinearLayout layEmtpy;
    @BindView(R.id.tv_msg)
    TextView tv_msg;

    private SimpleDialog simpleDialog;
    private BaseActivity activity;
    private FragmentFifthAdapter fragmentFifthAdapter;
    private List<OrderBean.InfoBean> orderInfos = new ArrayList<>();
    private BroadcastReceiver broadcastReceiver;
    private final int REQUEST_EVALUATE = 222;

    public static OrderFivthFragment getInstance() {
        OrderFivthFragment sf = new OrderFivthFragment();
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.order_one_fragment, null);
        ButterKnife.bind(this, rootview);
        activity = (BaseActivity) getActivity();
        initView();
        return rootview;
    }

    private void initView() {
        fragmentFifthAdapter = new FragmentFifthAdapter(activity, orderInfos);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new HorizDecoration(20));
        fragmentFifthAdapter.setOnDataLoadFinish(this);
        fragmentFifthAdapter.loadDataFirstTime();
        recyclerView.setAdapter(fragmentFifthAdapter);

        fragmentFifthAdapter.setOnClickListener(new FragmentFifthAdapter.MyItemClickLinstener() {
            @Override
            public void OnDeleteClickListener(FragmentFifthAdapter adapter, final int position, View view) {  //删除订单
                simpleDialog = new SimpleDialog(getContext(), "是否删除该订单?", "再想想", "确定", new SimpleDialog.OnButtonClick() {
                    @Override
                    public void onNegBtnClick() {
                        simpleDialog.cancel();
                    }

                    @Override
                    public void onPosBtnClick() {

                        int orderId = Integer.valueOf(orderInfos.get(position).getO_id());
                        deleteOrder(orderId, position);
                    }
                });
                simpleDialog.show();
            }

            @Override
            public void OnPingJiaClickListener(FragmentFifthAdapter adapter, int position, View view) {
                Intent intent = new Intent(activity, EvaluateActivity.class);
                intent.putExtra("orderId", orderInfos.get(position).getO_id());
                startActivityForResult(intent, REQUEST_EVALUATE);
            }
        });
    }

    private void deleteOrder(int orderId, final int position) {
        SharedPreferences sp = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderId", orderId);

        XUtil.Post(Url.ORDER_DELORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("re"))) {
                        fragmentFifthAdapter.removeItem(position);
                    }
                    ToastUtils.showToast(getContext(), jsonObject.optString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_EVALUATE)
            if (resultCode == RESULT_OK) {
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    fragmentFifthAdapter.loadDataFirstTime();
                }
                super.onActivityResult(requestCode, resultCode, data);
            }
    }

    @Override
    public void loadDataFinished(int datasLength) {
        if (datasLength == 0) {
            layEmtpy.setVisibility(View.VISIBLE);
            tv_msg.setText("暂无待评价订单~");
            recyclerView.setVisibility(View.GONE);
        } else {
            layEmtpy.setVisibility(View.GONE);
        }
    }
}